<template>
	<view class="container">
		<view v-if="loading" class="loading-box">
			<uni-load-more status="loading"></uni-load-more>
		</view>
		
		<view v-else-if="notificationData" class="notification-detail">
			<!-- 通知标题 -->
			<view class="notification-header">
				<view class="notification-title">{{notificationData.title}}</view>
				<view class="notification-meta">
					<text class="notification-category">{{notificationData.category}}</text>
					<text class="notification-date">{{formatDate(notificationData.create_time)}}</text>
				</view>
			</view>
			
			<!-- 通知内容 -->
			<view class="notification-content">
				<text class="content-text">{{notificationData.content}}</text>
			</view>
			
			<!-- 相关操作 -->
			<view class="notification-actions" v-if="notificationData.related_id && notificationData.type !== 'system'">
				<button class="action-btn" @click="handleRelatedAction">查看相关内容</button>
			</view>
			
			<!-- 删除按钮 -->
			<view class="delete-section">
				<button class="delete-btn" @click="deleteNotification">删除此通知</button>
			</view>
		</view>
		
		<view v-else class="error-box">
			<text class="error-text">通知不存在或已被删除</text>
			<button class="back-btn" @click="goBack">返回</button>
		</view>
	</view>
</template>

<script>
	import { getToken } from '../../utils/tokenManager.js';
	
	export default {
		data() {
			return {
				loading: true,
				notificationData: null,
				notificationId: '',
				userInfo: {}
			}
		},
		onLoad(options) {
			if (options.id) {
				this.notificationId = options.id;
				this.getUserInfo();
				this.getNotificationDetail();
			} else {
				uni.showToast({
					title: '参数错误',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		},
		methods: {
			// 获取用户信息
			getUserInfo() {
				const userInfoStr = uni.getStorageSync('userInfo');
				if (userInfoStr) {
					try {
						this.userInfo = JSON.parse(userInfoStr);
					} catch (e) {
						console.error('解析用户信息失败', e);
					}
				}
			},
			
			// 获取通知详情
			async getNotificationDetail() {
				try {
					uni.showLoading({ title: '加载中...' });
					
					const notificationService = uniCloud.importObject('notification-service');
					const res = await notificationService.getNotificationDetail(this.notificationId, this.userInfo._id);
					
					uni.hideLoading();
					
					if (res.code === 0) {
						this.notificationData = res.data;
						// 云对象已经自动处理了标记为已读的逻辑，这里不需要额外调用
					} else {
						uni.showToast({
							title: res.message || '获取通知详情失败',
							icon: 'none'
						});
					}
				} catch (err) {
					uni.hideLoading();
					console.error('获取通知详情失败:', err);
					uni.showToast({
						title: '获取通知详情失败: ' + (err.message || '网络错误，请稍后再试'),
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			
			// 处理相关操作
			handleRelatedAction() {
				if (!this.notificationData.related_id) return;
				
				const { type, related_id, extra_data } = this.notificationData;
				
				// 优先使用extra_data中的跳转信息
				if (extra_data && extra_data.jump_url) {
					// 特殊处理选派表跳转
					if (extra_data.jump_type === 'selection_table') {
						this.handleSelectionTableJump(extra_data);
						return;
					}
					
					uni.navigateTo({
						url: extra_data.jump_url
					});
					return;
				}
				
				switch (type) {
					case 'match_publish':
						// 跳转到比赛详情
						uni.navigateTo({
							url: `/packgeCompetition/competition/detail?id=${related_id}`
						});
						break;
					case 'match_review':
						// 根据extra_data决定跳转位置
						if (extra_data && extra_data.jump_type === 'selection_table') {
							// 跳转到选派表
							this.handleSelectionTableJump(extra_data);
						} else if (extra_data && extra_data.match_id) {
							// 如果有具体的比赛ID，跳转到比赛详情
							uni.navigateTo({
								url: `/packgeCompetition/competition/detail?id=${extra_data.match_id}`
							});
						} else {
							// 否则跳转到我的报名
							uni.navigateTo({
								url: `/packageMy/my/application-list`
							});
						}
						break;
					case 'credential_update':
						// 跳转到认证相关页面
						if (extra_data && extra_data.credential_type && extra_data.credential_id) {
							// 身份认证通知
							uni.navigateTo({
								url: `/packageMy/my/credential-detail?type=${extra_data.credential_type}&id=${extra_data.credential_id}`
							});
						} else if (extra_data && extra_data.certificate_id) {
							// 证书审核通知
							uni.navigateTo({
								url: `/packageMy/my/certificate-detail?id=${extra_data.certificate_id}`
							});
						} else {
							// 默认跳转到我的证书
							uni.navigateTo({
								url: `/packageMy/my/certificates`
							});
						}
						break;
					case 'referee_evaluation':
						// 跳转到执裁记录详情
						if (extra_data && extra_data.record_id) {
							uni.navigateTo({
								url: `/packageMy/my/match-record-detail?id=${extra_data.record_id}`
							});
						} else {
							// 备用跳转到执裁记录列表
							uni.navigateTo({
								url: `/packageMy/my/match-records`
							});
						}
						break;
					case 'match_invitation':
						// 跳转到邀请详情页面
						if (extra_data && extra_data.invitation_ids && extra_data.invitation_ids.length > 0) {
							// 如果有邀请ID，跳转到邀请详情
							uni.navigateTo({
								url: `/packgeCompetition/competition/invitation-detail?invitationId=${extra_data.invitation_ids[0]}`
							});
						} else if (extra_data && extra_data.match_id) {
							// 否则跳转到比赛详情
							uni.navigateTo({
								url: `/packgeCompetition/competition/detail?id=${extra_data.match_id}`
							});
						} else {
							uni.showToast({
								title: '邀请信息不完整',
								icon: 'none'
							});
						}
						break;
					case 'invitation_response':
						// 跳转to邀请回复相关页面
						if (extra_data && extra_data.invitation_id) {
							// 跳转到邀请详情查看回复
							uni.navigateTo({
								url: `/packgeCompetition/competition/invitation-detail?invitationId=${extra_data.invitation_id}`
							});
						} else if (extra_data && extra_data.match_id) {
							// 跳转到比赛详情
							uni.navigateTo({
								url: `/packgeCompetition/competition/detail?id=${extra_data.match_id}`
							});
						} else {
							uni.showToast({
								title: '相关信息不完整',
								icon: 'none'
							});
						}
						break;
					default:
						uni.showToast({
							title: '暂无相关操作',
							icon: 'none'
						});
						break;
				}
			},
			
			// 删除通知
			async deleteNotification() {
				uni.showModal({
					title: '提示',
					content: '确定要删除这条通知吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({ title: '删除中...' });
								
								const notificationService = uniCloud.importObject('notification-service');
								const result = await notificationService.deleteNotification(this.notificationId, this.userInfo._id);
								
								uni.hideLoading();
								
								if (result.code === 0) {
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									});
									
									setTimeout(() => {
										uni.navigateBack();
									}, 1500);
								} else {
									uni.showToast({
										title: result.message || '删除失败',
										icon: 'none'
									});
								}
							} catch (err) {
								uni.hideLoading();
								console.error('删除通知失败:', err);
								uni.showToast({
									title: '网络错误，请稍后再试',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			
			// 返回
			goBack() {
				uni.navigateBack();
			},
			
			// 处理选派表跳转
			async handleSelectionTableJump(extraData) {
				try {
					uni.showLoading({ title: '加载选派表...' });
					
					console.log('=== handleSelectionTableJump - 开始处理选派表跳转 ===');
					console.log('传入的 extraData:', JSON.stringify(extraData, null, 2));
					console.log('当前用户信息:', this.userInfo);
					
					// 获取选派表数据
					const matchScheduleObject = uniCloud.importObject('match-schedule-object');
					const selectionData = extraData.selection_data || {};
					
					// 详细分析参数构造
					console.log('提取的 selectionData:', JSON.stringify(selectionData, null, 2));
					console.log('extraData.session_id:', extraData.session_id);
					console.log('selectionData.session_ids:', selectionData.session_ids);
					
					const sessionIds = selectionData.session_ids || (extraData.session_id ? [extraData.session_id] : []);
					console.log('最终构造的 sessionIds:', sessionIds);
					
					if (!sessionIds || sessionIds.length === 0) {
						uni.hideLoading();
						console.error('sessionIds 为空，无法查询选派表');
						uni.showToast({
							title: '通知数据不完整，无法查看选派表',
							icon: 'none'
						});
						return;
					}
					
					const queryParams = {
						sessionIds: sessionIds,
						viewerRole: selectionData.viewer_role || 'referee',
						viewerId: this.userInfo._id,
						onlyConfirmed: selectionData.only_confirmed !== false // 默认为true，除非明确设置为false
					};
					
					console.log('=== 云对象查询参数 ===');
					console.log('参数详情:', JSON.stringify(queryParams, null, 2));
					
					const result = await matchScheduleObject.getRoundSelectionSummary(queryParams);
					
					console.log('=== 云对象查询结果 ===');
					console.log('result.code:', result.code);
					console.log('result.message:', result.message);
					console.log('result.data:', JSON.stringify(result.data, null, 2));
					
					uni.hideLoading();
					
					if (result.code === 0) {
						if (!result.data || !result.data.matches || result.data.matches.length === 0) {
							console.log('=== 数据为空的情况分析 ===');
							console.log('result.data存在?', !!result.data);
							console.log('result.data.matches存在?', !!(result.data && result.data.matches));
							console.log('result.data.matches长度:', result.data && result.data.matches ? result.data.matches.length : 'N/A');
							
							uni.showModal({
								title: '提示',
								content: '未找到对应的选派数据，可能数据还未生成或权限不足。请联系管理员确认。',
								showCancel: false,
								confirmText: '我知道了'
							});
							return;
						}
						
						// 将数据存储到本地，避免URL过长
						const scheduleKey = `schedule_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
						uni.setStorageSync(scheduleKey, result.data);
						
						console.log('=== 准备跳转选派表 ===');
						console.log('存储key:', scheduleKey);
						console.log('存储的数据概要:', {
							series_title: result.data.series_title,
							total_matches: result.data.total_matches,
							total_selected: result.data.total_selected,
							matches_count: result.data.matches ? result.data.matches.length : 0
						});
						
						// 跳转到选派表查看页面，高亮当前用户
						uni.navigateTo({
							url: `/packageMy/my/schedule-viewer?key=${scheduleKey}&role=referee&highlightUser=${this.userInfo._id}`
						});
					} else {
						console.error('=== 云对象调用失败 ===');
						console.error('错误代码:', result.code);
						console.error('错误信息:', result.message);
						
						uni.showToast({
							title: result.message || '获取选派表失败',
							icon: 'none',
							duration: 3000
						});
					}
				} catch (error) {
					uni.hideLoading();
					console.error('=== handleSelectionTableJump 异常 ===');
					console.error('异常详情:', error);
					console.error('异常堆栈:', error.stack);
					
					uni.showToast({
						title: '获取选派表失败: ' + (error.message || '网络错误'),
						icon: 'none',
						duration: 3000
					});
				}
			},
			
			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return '';
				
				const date = new Date(dateStr);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hour = date.getHours().toString().padStart(2, '0');
				const minute = date.getMinutes().toString().padStart(2, '0');
				
				return `${year}-${month}-${day} ${hour}:${minute}`;
			}
		}
	}
</script>

<style>
.container {
	padding: 30rpx;
	background-color: #F8F8F8;
	min-height: 100vh;
}

.loading-box {
	padding: 100rpx 0;
	display: flex;
	justify-content: center;
}

.notification-detail {
	
}

.notification-header {
	background-color: #FFFFFF;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.notification-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 20rpx;
	line-height: 1.4;
}

.notification-meta {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	color: #999999;
	font-size: 24rpx;
}

.notification-category {
	padding: 4rpx 12rpx;
	background-color: #F0F0F0;
	border-radius: 12rpx;
	margin-right: 20rpx;
}

.notification-date {
	
}

.notification-content {
	background-color: #FFFFFF;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.content-text {
	font-size: 28rpx;
	color: #333333;
	line-height: 1.6;
}

.notification-actions {
	background-color: #FFFFFF;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.action-btn {
	width: 100%;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	background-color: #1BAE76;
	color: #FFFFFF;
	border-radius: 10rpx;
	font-size: 28rpx;
	border: none;
}

.delete-section {
	background-color: #FFFFFF;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.delete-btn {
	width: 100%;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	background-color: #FF4757;
	color: #FFFFFF;
	border-radius: 10rpx;
	font-size: 28rpx;
	border: none;
}

.error-box {
	padding: 100rpx 0;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.error-text {
	font-size: 28rpx;
	color: #999;
	margin-bottom: 30rpx;
}

.back-btn {
	padding: 20rpx 40rpx;
	background-color: #1BAE76;
	color: #FFFFFF;
	border-radius: 10rpx;
	font-size: 28rpx;
	border: none;
}
</style> 